package com.linln.admin.pcs.api;

import com.alibaba.fastjson.JSONObject;
import com.linln.admin.pcs.service.WechatPayRefundService;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.util.Map;

@RestController
@RequestMapping("/api/wx/")
public class WeChatController {

    private final static Logger logger = LoggerFactory.getLogger(WeChatController.class);

    @Value("${wx.appId}")
    private String APPID;

    @Value("${wx.appSecret}")
    private String SECRET;

    /**
     * 获取微信配置
     * @param url 当前页面的URL
     * @return
     */
    @GetMapping("config")
    public ResultVo getWxConfig(@RequestParam("url") String url) {
        logger.error("获取微信配置:url"+url);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000); // 时间戳
        String nonceStr = generateNonceStr(); // 随机字符串
        String signature = generateSignature(timestamp, nonceStr, url); // 签名

        Map<String, String> map = Map.of(
                "appId", APPID,
                "timestamp", timestamp,
                "nonceStr", nonceStr,
                "signature", signature
        );
        logger.error("授权配置:"+map);
        return ResultVoUtil.success(map);
    }

    /**
     * 获取微信授权
     * @param code
     * @return
     */
    @GetMapping("auth")
    public ResultVo handleAuth(@RequestParam("code") String code) {
        logger.error("获取微信授权code"+code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" +APPID+
                "&secret=" +SECRET+
                "&code=" + code +
                "&grant_type=authorization_code";

        RestTemplate restTemplate = new RestTemplate();

        String response = restTemplate.getForObject(url, String.class);

        // 解析返回的 JSON 数据
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (ObjectUtils.isNotEmpty(jsonObject)){
            if (jsonObject.containsKey("openid")) {
                String openid = jsonObject.getString("openid");
                logger.error("获取微信授权jsonObject:"+openid);
                return ResultVoUtil.success("授权成功",openid);
            }else {
                return ResultVoUtil.error(String.valueOf(jsonObject));
            }

        } else {
            return ResultVoUtil.error(String.valueOf(jsonObject));
        }
    }

    private String generateNonceStr() {
        return java.util.UUID.randomUUID().toString().replaceAll("-", "");
    }

    private String generateSignature(String timestamp, String nonceStr, String url) {
        String token = getAccessToken();
        String string1 = "jsapi_ticket=" + getJsApiTicket(token) +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;

        try {
            return DigestUtils.sha1Hex(string1);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String getAccessToken() {
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?"
                + "grant_type=client_credential"
                + "&appid=" + APPID
                + "&secret=" + SECRET;

        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(accessTokenUrl, String.class);
        JSONObject jsonObject = JSONObject.parseObject(response);

        if (jsonObject.containsKey("access_token")) {
            return jsonObject.getString("access_token");
        } else {
            throw new RuntimeException("获取 access_token 失败：" + jsonObject.getString("errmsg"));
        }
    }

    // 获取 jsapi_ticket
    private String getJsApiTicket(String accessToken) {
        String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?"
                + "access_token=" + accessToken
                + "&type=jsapi";

        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(ticketUrl, String.class);
        JSONObject jsonObject = JSONObject.parseObject(response);

        if (jsonObject.containsKey("ticket")) {
            return jsonObject.getString("ticket");
        } else {
            throw new RuntimeException("获取 jsapi_ticket 失败：" + jsonObject.getString("errmsg"));
        }
    }
}
